package com.atguigu.exer;

import com.atguigu.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Scanner;

/**
 * 课后练习2
 *
 * @author admin
 */
public class ExerTest2 {

    /**
     * 问题1：向 examstudent 表中添加一条记录
     */
    @Test
    public void testInsert() throws Exception {
        Scanner scanner = new Scanner(System.in);
        System.out.print("四级/六级：");
        int type = scanner.nextInt();
        System.out.print("身份证号：");
        String IDCard = scanner.next();
        System.out.print("准考证号：");
        String ExamCard = scanner.next();
        System.out.print("学生姓名：");
        String studentName = scanner.next();
        System.out.print("所在城市：");
        String location = scanner.next();
        System.out.print("考试成绩：");
        int grade = scanner.nextInt();

        String sql = "insert into examstudent(Type, IDCard, ExamCard, StudentName, Location, Grade) value (?, ?, ?, ?, ?, ?)";
        int insertCount = update(sql, type, IDCard, ExamCard, studentName, location, grade);
        System.out.println(insertCount > 0 ? "添加成功" : "添加失败");
    }

    /**
     * 通用的增删改操作
     * sql 中占位符的个数与可变形参的长度相同！
     */
    public int update(String sql, Object... args) throws Exception {

        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            // 1.获取数据库连接
            connection = JDBCUtils.getConnection();

            // 2.预编译 sql 语句，返回 PreparedStatement 实例对象
            preparedStatement = connection.prepareStatement(sql);

            // 3.填充占位符  小心参数声明错误！！！
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            /**
             * 4.执行
             * preparedStatement.execute()
             * 如果执行的是查询操作，有返回结果，则此方法返回 true
             * 如果执行的是增、删、改操作，没有返回结果，则此方法返回 false
             */
            return preparedStatement.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5.资源的关闭
            JDBCUtils.closeResource(connection, preparedStatement);
        }

        return 0;

    }

    /**
     * 问题2：根据身份证号或者准考证号查询学生成绩信息
     */
    @Test
    public void queryWithIDCardOrExamCard() {
        System.out.println("请选择您要输入的类型");
        System.out.println("a.准考证号");
        System.out.println("b.身份证号");

        Scanner scanner = new Scanner(System.in);
        String selection = scanner.next();

        if ("a".equalsIgnoreCase(selection)) {
            System.out.println("请输入准考证号：");
            String examCard = scanner.next();

            String sql = "select FlowID flowID, Type type, IDCard, ExamCard examCard, StudentName name, Location location, Grade grade from examstudent where ExamCard = ?";
            Student student = getInstance(Student.class, sql, examCard);
            if (student != null) {
                System.out.println(student);
            } else {
                System.out.println("输入的准考证号有误");
            }
        } else if ("b".equalsIgnoreCase(selection)) {
            System.out.println("请输入身份证号：");
            String IDCard = scanner.next();

            String sql = "select FlowID flowID, Type type, IDCard, ExamCard examCard, StudentName name, Location location, Grade grade from examstudent where IDCard = ?";
            Student student = getInstance(Student.class, sql, IDCard);
            if (student != null) {
                System.out.println(student);
            } else {
                System.out.println("输入的身份证号有误");
            }
        } else {
            System.out.println("您的输入有误，请重新进入程序");
        }
    }

    /**
     * 针对于不同的表的通用的查询操作，返回表中的一条记录
     *
     * @param clazz
     * @param sql
     * @param args
     * @param <T>
     * @return
     */
    public <T> T getInstance(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 1.获取连接
            connection = JDBCUtils.getConnection();

            // 2.预编译 sql 语句，返回 PreparedStatement 实例
            preparedStatement = connection.prepareStatement(sql);

            // 3.填充占位符
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            // 4.执行，并返回结果集
            resultSet = preparedStatement.executeQuery();
            // 获取结果集的元数据 ResultSetMetaData
            ResultSetMetaData rsmd = resultSet.getMetaData();
            // 通过 ResultSetMetaData 获取结果集中的列数
            int columnCount = rsmd.getColumnCount();

            // 5.处理结果集
            if (resultSet.next()) {
                T t = clazz.newInstance();

                // 处理结果集一行数据中的每一列
                for (int i = 0; i < columnCount; i++) {
                    // 获取列值
                    Object columnValue = resultSet.getObject(i + 1);

                    // 获取每个列的列名
                    String columnLabel = rsmd.getColumnLabel(i + 1);

                    // 给 customers 对象指定 columnName 属性，赋值为 columnValue   通过反射
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6.关闭资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }

    /**
     * 问题3：删除指定的学生信息
     * testDeleteByExmaCard()
     */
    @Test
    public void testDeleteByExmaCard() throws Exception {
        System.out.println("请输入学生的考号：");
        Scanner scanner = new Scanner(System.in);
        String examCard = scanner.next();

        // 查询指定准考证号的学生
        String sql = "select FlowID flowID, Type type, IDCard, ExamCard examCard, StudentName name, Location location, Grade grade from examstudent where ExamCard = ?";
        Student student = getInstance(Student.class, sql, examCard);
        if (student == null) {
            System.out.println("查无此人，请重新输入");
        } else {
            String sql1 = "delete from examstudent where ExamCard = ?";
            int deleteCount = update(sql1, examCard);
            System.out.println(deleteCount > 0 ? "删除成功" : "删除失败");
        }
    }

    /**
     * 优化操作
     *
     * @throws Exception
     */
    @Test
    public void testDeleteByExmaCard1() throws Exception {
        System.out.println("请输入学生的考号：");
        Scanner scanner = new Scanner(System.in);
        String examCard = scanner.next();

        String sql = "delete from examstudent where ExamCard = ?";
        int deleteCount = update(sql, examCard);
        System.out.println(deleteCount > 0 ? "删除成功" : "查无此人，请重新输入");
    }
}
